package com.kangyi.app.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.kangyi.app.mapper.*;
import com.kangyi.app.service.NursingHomeServices;
import com.kangyi.dto.AppNursingPageQueryDTO;
import com.kangyi.dto.FavoriteDTO;
import com.kangyi.dto.NursingHomeDetailDTO;
import com.kangyi.entity.NursingHomeFavorite;
import com.kangyi.exception.DataNotExistException;
import com.kangyi.result.ListPageResult;
import com.kangyi.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Blank
 * @version 1.0
 */
@Service
public class NursingHomeServicesImpl implements NursingHomeServices {

    @Autowired
    private NursingHomeMapper nursingHomeMapper;

    @Autowired
    private RegionMapper regionMapper;

    @Autowired
    private NursingHomeTagMapper nursingHomeTagMapper;

    @Autowired
    private FeeMapper feeMapper;

    @Autowired
    private NursingHomeRequirementMapper nursingHomeRequirementMapper;

    @Autowired
    private NursingHomeServiceMapper nursingHomeServiceMapper;

    @Autowired
    private NursingHomeEventMapper nursingHomeEventMapper;

    @Autowired
    private NursingHomeReviewMapper nursingHomeReviewMapper;

    @Autowired
    private NursingHomeReviewImageMapper nursingHomeReviewImageMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private NursingHomeFavoriteMapper nursingHomeFavoriteMapper;

    // 封装获取养老院标签的方法，提高代码复用性
    private Map<Integer, List<NursingHomeTagVO>> getNursingHomeTagsMap(List<Integer> nursingHomeIds) {
        List<NursingHomeTagVO> nursingHomeTagVOs = nursingHomeTagMapper.getTagsByNursingHomeIds(nursingHomeIds);
        return nursingHomeTagVOs.stream()
                .collect(Collectors.groupingBy(NursingHomeTagVO::getNursingHomeId));
    }

    @Override
    public ListPageResult list(AppNursingPageQueryDTO appNursingPageQueryDTO) {
        //获取地区id
        Integer regionId = regionMapper.getId(appNursingPageQueryDTO.getProvince(),appNursingPageQueryDTO.getCity(),appNursingPageQueryDTO.getDistrict());
        PageHelper.startPage(appNursingPageQueryDTO.getPage(),appNursingPageQueryDTO.getPageSize());
        Page<AppNursingListVO> page = nursingHomeMapper.list(appNursingPageQueryDTO,regionId);
        long total = page.getTotal();
        List<AppNursingListVO> result = page.getResult();
        for (AppNursingListVO vo : result) {
            //标签
            List<String> tags = nursingHomeTagMapper.getTags(vo.getId());
            vo.setTags(tags);
            //房型价格，最低价
            BigDecimal fee = feeMapper.getFee(vo.getId());
            vo.setPrice(fee);
        }
        return new ListPageResult(total,appNursingPageQueryDTO.getPage(),appNursingPageQueryDTO.getPageSize(),result);
    }

    @Override
    public NursingHomeDetailVO inquiryNursingHomeById(NursingHomeDetailDTO nursingHomeDetailDTO) {
        Integer id = nursingHomeDetailDTO.getNursingHomeId();

        // 1. 查询养老院基本信息（包含数据库计算好的评分）
        NursingHomeDetailVO nursingHomeDetailVO = nursingHomeMapper.getNursingHomeById(id);
        if (nursingHomeDetailVO == null) {
            throw new DataNotExistException("养老院不存在");
        }

        List<Integer> nursingHomeIds = Collections.singletonList(id);

        // 2. 查询养老院标签
        Map<Integer, List<NursingHomeTagVO>> tagMap = getNursingHomeTagsMap(nursingHomeIds);
        nursingHomeDetailVO.setNursingHomeTagVOList(tagMap.getOrDefault(id, new ArrayList<>()));

        // 3. 查询养老院收费信息
        List<FeeVO> feeVOList = feeMapper.inquiryNursingHomeFees(id);
        nursingHomeDetailVO.setFeeVOList(feeVOList);

        // 4. 查询养老院特色服务
        List<NursingHomeServiceVO> serviceVOList = nursingHomeServiceMapper.inquiryNursingHomeServices(id);
        nursingHomeDetailVO.setNursingHomeServiceVOList(serviceVOList);

        // 5. 查询养老院精彩活动
        List<NursingHomeEventVO> eventList = nursingHomeEventMapper.inquiryNursingHomeEvents(id);
        nursingHomeDetailVO.setNursingHomeEventVOList(eventList);

        // 6. 查询养老院评论
        List<NursingHomeReviewVO> reviewList = nursingHomeReviewMapper.inquiryNursingHomeReviews(id);
        nursingHomeDetailVO.setNursingHomeReviewVOList(reviewList);
        nursingHomeDetailVO.setTotalReview(reviewList.size()); // 设置评论总条数

        if (!reviewList.isEmpty()) {
            // 6.1 收集所有评论 ID
            List<Integer> reviewIds = reviewList.stream()
                    .map(NursingHomeReviewVO::getId)
                    .collect(Collectors.toList());

            // 6.2 批量查询所有评论的图片，并按 sort 排序
            List<NursingHomeReviewImageVO> nursingHomeReviewImageVOList = nursingHomeReviewImageMapper.getImgsByReviewIdsSorted(reviewIds);

            // 6.3 按评论 ID 分组映射
            Map<Integer, List<NursingHomeReviewImageVO>> reviewImageVOMap = nursingHomeReviewImageVOList.stream()
                    .collect(Collectors.groupingBy(NursingHomeReviewImageVO::getNursingHomeReviewId));

            // 6.4 赋值图片列表到相应评论
            for (NursingHomeReviewVO reviewVO : reviewList) {
                reviewVO.setNursingHomeReviewImageVOList(reviewImageVOMap.getOrDefault(reviewVO.getId(), new ArrayList<>()));
            }

            // 6.5 收集所有评论的用户 ID
            List<Integer> userIds = reviewList.stream()
                    .map(NursingHomeReviewVO::getCreateUser)
                    .distinct()
                    .collect(Collectors.toList());

            if (!userIds.isEmpty()) {
                // 6.6 批量查询用户信息
                List<UserVO> userList = userMapper.getUsersByIds(userIds);

                // 6.7 转换为 Map，方便快速查找
                Map<Integer, UserVO> userMap = userList.stream()
                        .collect(Collectors.toMap(UserVO::getId, user -> user));

                // 6.8 赋值用户数据到评论，并隐藏手机号后 6 位
                for (NursingHomeReviewVO reviewVO : reviewList) {
                    UserVO userVO = userMap.get(reviewVO.getCreateUser());
                    if (userVO != null) {
                        // 处理手机号隐藏后 6 位
                        if (userVO.getPhone() != null && userVO.getPhone().length() >= 6) {
                            String phone = userVO.getPhone();
                            userVO.setPhone(phone.substring(0, phone.length() - 6) + "******");
                        }
                        reviewVO.setUserVO(userVO);
                    }
                }
            }
        }

        // 9. 查询入住条件
        List<NursingHomeRequirementVO> requirementVOList = nursingHomeRequirementMapper.inquiryNursingHomeRequirements(id);
        nursingHomeDetailVO.setNursingHomeRequirementVOList(requirementVOList);

        // 当前用户id
        Integer userId = nursingHomeDetailDTO.getUserId();
        FavoriteDTO build = FavoriteDTO.builder()
                .nursingHomeId(id)
                .userId(userId).build();
        NursingHomeFavorite nursingHomeFavorite = nursingHomeFavoriteMapper.selectByUserIdAndNursingHomeId(build);
        nursingHomeDetailVO.setCollect(nursingHomeFavorite != null);

        return nursingHomeDetailVO;
    }
}
